<?php
/**
 * Creates select that allows searching and adding new elements. Allows selecting one or multiple values.
 * 
 * This class depentds on DomFgSelect!
* @author Oliver Leisalu, Inditel Meedia
* @package DomFg
* @subpackage Input
*/
class DomFgSearchSelect extends DomFgInput {
	
	/**
	 * Url where contents is taken. Content format must be json and format is [{'key':'some key','value'=>'some value'}[,...]]
	 *
	 * @var String
	 */
	protected $ajaxUrl;
	
	protected $allowAddingNew = false;
	
	protected $maxElements = 1;
	
	protected $selected = array();
	
	public function ajaxUrl( $ajaxUrl ) {
		$this->ajaxUrl = $ajaxUrl;
		return $this;
	}
	
	public function allowAddingNew( $allowAddingNew ) {
		$this->allowAddingNew = $allowAddingNew;
		return $this;
	}
	
	public function maxElements( $maxElements ) {
		$this->maxElements = $maxElements;
		return $this;
	}	
	
	/*
	 * Add selected list. Accepted arguments are everything that DomFgSelect allows as values.
	 * 
	 * There is one exception. If there is added only one element and it key and value is empty then this element is ignored.
	 * 
	 * @var Array $selected
	 */
	public function selected( $selected ) {
		$testEmpty = $selected;
		$testEmptyKey = array_pop(array_keys($selected));
		$testEmpty = array_pop($testEmpty);
		if( count($selected) == 1 && $testEmptyKey == '' && $testEmpty == '')
			$selected = array();
		
		$this->selected = DomFgSelect::parseArrayInput($selected, array(), NULL, NULL );
		return $this;
	}
	
	/**
	 * Returns list of items added to searchSelect.
	 * 
	 * Returns  array with elements key, value if maxElements == 1<br>
	 * Sample: array(key=>'Sample key', value=>'sample value)<br>
	 * <br>
	 * Returns array with arrays which keys are (key=>'', value=>'') if maxElements is creater than 1<br>
	 * Sample: array( array(key=>'Sample key', value=>'sample value) [,...])<br>
	 * 
	 * @param String $name
	 * @param Mixed $value
	 * @return Array
	 */
	public static function parsePost( $name, &$value ) {
		$list = array();
		
		$keys = explode('|',$value['keys']);
		$values = explode('|',$value['values']);
		foreach( $values as $i => $val ) {
			if( $keys[$i] != '' or $val != '') {
				$list[] = array('key' => $keys[$i], 'value' => htmlspecialchars_decode(stripslashes($val)) );
			}
		}
		
		if( $value['maxElements'] == 1 ) {
			return array_pop($list);	
		} else
			return $list;
	}
	
	public function render() {
		$renderer = $this->getRenderer();
		$renderer->assign('input', $this );
		return $renderer->fetch('Input/SearchSelect.html');
	}
}
?>